<?php
namespace App\Http;
use Mail;

trait Common 
{
    public function errorReturn($msg)
    {
        return response()->json(['status' => 0, 'msg' => $msg]);
    }

     public function successReturn($msg, $data=null)
    {
        return response()->json(['status' => 1, 'msg' => $msg, 'data' => $data]);
    }


    //发送邮件 发邮件 异常还没写 没有回滚数据库
    public function sendEmail($blade, $data)
    {
        //记录发送记录
        file_put_contents('sendEmail.log', json_encode($data).PHP_EOL,  FILE_APPEND);

        Mail::send($blade, $data, function($message) use ($data)
        {   
            $message->from('dma-service@webpowerchina.com', 'Webpowerchina');

            $message->to($data['email'])->subject('账号确认邮件——来自webpower!');
        });

    }


   	//随机数字或字母
    public function createPassword($len)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';

        $password = '';

        for ($i = 0; $i < $len; $i++){
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }

    //头响应禁止缓存 已经在middleware/NoCacheViewMiddleware实现
    public function noCacheView($view, $data)
    {   
        return response()->view($view, $data)->header('Cache-Control', 'no-cache,no-store,must-revalidate');
    }

    public function remoteCurl($url, $name, $method = 'GET', $data = null)
    {
        $ch = curl_init();  

        $timeout = 10;  

        curl_setopt ($ch, CURLOPT_URL, $url); //发贴地址  

        // $baseCode = "c21zLWRldjptYjNSd2Q4ejBWZkRvN3JFMHc0RWkvbm5aUmZTL1lGTnFGTm5OdEtvYzlZPQ====";
        // base64_encode('sms-dev:'.base64_encode(encrpt('sms-dev','sms@Webpower2015')));
        $env = env('APP_ENV');

        if($env == 'local'){
            $baseCode = base64_encode('sms-dev:'.base64_encode($this->remoteEncrypt('sms-dev')));
        }else{
            $baseCode = base64_encode("$name:".base64_encode($this->remoteEncrypt($name)));
        }

        $header = [];

        $header[] = "Authorization: Basic $baseCode";

        $header[] = "Content-type: application/json";
          
        curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);  
        
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  

        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  

        switch ($method){  
            case "GET" : 
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break; 

            case "POST": 
                curl_setopt($ch, CURLOPT_POST,true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                break;  

            case "PUT" : 
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                break;  

            case "DELETE":
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
                break;  
        }  

        $return = curl_exec($ch);

        if($return === false)
        {
            file_put_contents('curl_fail.log', curl_error($ch).PHP_EOL, FILE_APPEND);

            echo 'curl fail';

            die;

        }else{
            $rs = json_decode($return, true);//获得返回值  

            curl_close($ch);  

            return $rs;  
        }
       
        
    }

    public function remoteEncrypt($data)
    {   
        $cryptAlgorithm = config('remoteApi.cryptAlgorithm');

        $key = config('remoteApi.encryptkey');

        $module = @mcrypt_module_open($cryptAlgorithm,'', MCRYPT_MODE_CBC,'');

        srand();

        $iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);

        mcrypt_generic_init($module,$key,$iv);

        $encrypted=$iv.mcrypt_generic($module,$data);

        mcrypt_generic_deinit($module);

        mcrypt_module_close($module);

        return $encrypted;
    }

    public function currentUser()
    {
        return session('adminInfo')->email;
    }

    public function licenseName($license)
    {
        $rs = explode('.', $license);

        return $rs[0];
    }


    //替换url
    public function currentUrl($licenseName, $path)
    {
        $url = str_replace('{license name}', $licenseName, config('remoteApi.baseUrl')).$path;

        return $url;
    }

    //获取结果
    public function remoteReturn($license, $path, $method, $data = null, $id = null)
    {
        $env = env('APP_ENV');

        $licenseName = $this->licenseName($license);

        if($env == 'local'){
            $url = config('remoteApi.testUrl').$path;
        }else{
            $url = $this->currentUrl($licenseName, $path);
        }

        if($id){
            $url .= '/'. $id;
        }

        $rs = $this->remoteCurl($url, $licenseName, $method, $data);

        return $rs;
    }

    /**
     * 返回不同环境下的图片路径
     * @return mixed
     */
    public function getImgUrl()
    {
        $imgUrl = '';
        if('dev' == env('APP_ENV')){
            $imgUrl = env('QINIU_IMG_URL_DEV');
        }elseif('test' == env('APP_ENV')){
            $imgUrl = env('QINIU_IMG_URL_TEST');
        }elseif('pro' == env('APP_ENV')){
            $imgUrl = env('QINIU_IMG_URL');
        }
        return $imgUrl;
    }

    /**
     * 返回当前环境
     * @return mixed
     */
    public function getAppEnv()
    {
        return env('APP_ENV');
    }

    /**
     * 获取货币代码
     * @return array
     */
    public function getCurrencyArr()
    {
        $arr = [
            ['id' => 'USD', 'name' => 'USD'],
            ['id' => 'GBP', 'name' => 'GBP'],
            ['id' => 'CNY', 'name' => 'CNY'],
        ];
        return $arr;
    }

}